<template>
  <div class="app-container">
    <FilterSearch :value="queryParams" :config="configData" :labelCol="8" :wrapperCol="16" layout="inline">
    </FilterSearch>
    <main>
      <div class="table">
        <a-table :scroll="{ x: 1400 }" bordered :dataSource="tableData.dataSource" :columns="tableData.columns"
          :pagination="false" :loading="tableData.loading">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="handleChange(record, 'finish')" v-if="record.status != 404">
                完成
              </a-button>
              <a-button type="link" @click="handleChange(record, 'details')">
                详情
              </a-button>
              <a-button type="link" @click="handleChange(record, 'remove')" v-if="record.status != 404">
                删除
              </a-button>
            </template>
            <template v-if="column.key === 'createdBy'">
              <span>
                {{ record.createdByName }}
              </span>
            </template>
            <template v-if="column.key == 'archivesNum'">
              {{ record.archivesNum }}/{{ record.actualArchivesNum }}
            </template>
            <template v-if="column.key === 'status'">
              <template v-for="item in typeOptions.options1">
                <span v-if="record.status == item.codeValue" color="#f50">{{ item.codeName }}</span>
              </template>
            </template>
          </template>
        </a-table>
      </div>
      <div class="page">
        <a-pagination v-model:current="queryParams.pageNumber" :show-total="total => ` 总条数:${total}条`" v-model:pageSize="queryParams.pageSize"
          :total="tableData.total" @change="currentChange" />
      </div>
    </main>

    <a-modal v-model:open="modalOpen.open1" style="width:500px;" title="添加任务" :maskClosable="false" :closable="false">
      <div class="modal-body">
        <a-form :model="formState" ref="formRef" :rules="rules" :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }"
          autocomplete="off">
          <a-row>
            <a-col :span="24">
              <a-form-item label="任务名称" name="task">
                <a-input v-model:value="formState.task" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="档案存储地" name="fileLocation">
                <a-select allowClear v-model:value="formState.stashId" @change="stashChange" style="width:33%;" placeholder="请选择">
                  <a-select-option v-for="(item, index) in typeOptions.options2" :value="item.id" :key="index">
                    {{ item.stashName }}
                  </a-select-option>
                </a-select>
                <a-select allowClear v-model:value="formState.frameNum" @change="frameNumChange" style="width:33%;"
                  placeholder="请选择">
                  <a-select-option v-for="(item, index) in typeOptions.options4" :value="item.frameNum" :key="index">
                    {{ item.frameNum }}
                  </a-select-option>
                </a-select>
                <a-select allowClear v-model:value="formState.stashDetailId" style="width:33%;" placeholder="请选择">
                  <a-select-option v-for="(item, index) in typeOptions.options5" :value="item.id" :key="index">
                    {{ item.rowNum }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="距离上次盘库时间" name="yearType">
                <a-select allowClear v-model:value="formState.yearType" placeholder="请选择">
                  <a-select-option v-for="(item, index) in typeOptions.options3" :value="item.codeValue" :key="index">
                    {{ item.codeName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="入库时间" name="warehouseTime">
                <a-range-picker style="width:100%;" valueFormat="YYYY-MM-DD" v-model:value="formState.warehouseTime" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn">
            <a-button @click="handleChange({}, 'task')" type="primary">确认</a-button>
          </div>
          <div class="modal-btn">
            <a-button @click="cancel('task')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>

    <a-modal v-model:open="modalOpen.open2" style="width:500px;" :title="modalOpen.modalTit" :maskClosable="false"
      :closable="false">
      <div class="modal-body">
        <p>
          {{ modalOpen.modalDesc }}
        </p>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn">
            <a-button @click="handleChange({}, 'finishOk')" type="primary">确认</a-button>
          </div>
          <div class="modal-btn">
            <a-button @click="cancel('finish')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { computed, ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { user as useUser } from "@/store";
import { getList, updateTask, removeTask, createTask } from "@/api/commerProcess";
import { getQueryAll, getStashList, getStashListInfo } from "@/api/common";
import { message } from 'ant-design-vue';
import { MATERIAL } from '@/utils/config';
import { getUserInfo } from '@/api/login';
import { dedup } from "@/utils/index";

const user = useUser();
const router = useRouter();
const queryParams = ref({
  pageNumber: 1,
  pageSize: 10,

});
const formRef = ref({});
const modalOpen = reactive({
  open1: false,
  open2: false,
  open3: false,
  modalTit: '完成',
  modalDesc: '是否确认完成任务?',
  status: ""
});
const typeOptions = reactive({
  options1: [],
  options2: [],
  options3: [],
  options4: [],
  options5: []
});
const tableData = reactive({
  dataSource: [],
  columns: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      align: 'center'
    },
    {
      title: '任务名称',
      dataIndex: 'task',
      key: 'task',
    },
    {
      title: '创建人',
      dataIndex: 'createdByName',
      key: 'createdByName'
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime'
    },
    {
      title: '盘库进度',
      dataIndex: 'archivesNum',
      key: 'archivesNum',
    },
    {
      title: '任务状态',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: '任务完成时间',
      dataIndex: 'taskCompleteTime',
      key: 'taskCompleteTime',
    },
    {
      title: '操作',
      key: 'action',
      width: 220,
      fixed: 'right'
    },
  ],
  total: 0,
  loading: false
});
interface FormState {
  stashId: any;
  frameNum: any;
  stashDetailId: any;
  [props: string]: string | number | Array<object> | Array<string>;
  warehouseTime: Array<string>;
}
let formState: FormState = reactive({
  warehouseTime: [],
  warehouseStartTime: "",
  warehouseEndTime: "",
  stashId: null,
  frameNum: null,
  stashDetailId: null
});
const configData = computed(() => {
  let config = {
    itemConfig: [],
    operate: [
      {
        icon: "",
        type: "primary",
        name: "添加任务",
        handleClick: insertWorK,
        rule: true,
      }
    ],
    rules: {

    },
  };
  return config;
});
const rules = computed(() => {
  let rules = {
    task: [{ required: true, message: "请输入", trigger: "blur" }],
  };
  return rules;
});
function getLoad() {
  tableData.loading = true;
  getList({ inventoryFlag: MATERIAL.YEARTASKTYPE, ...queryParams.value }).then(async (res: any) => {
    for (const key in res.records) {
      res.records[key]['createdByName'] = await getUserInfo({ createGlobalUserId: res.records[key]['createdBy'] });
    }
    tableData.dataSource = res.records;
    tableData.total = res.total;
    tableData.loading = false;
  });
}
function getOptionsList() {
  getQueryAll({ codeType: 'taskStatusType' }).then((res: any) => {
    typeOptions.options1 = res;
  });
  getQueryAll({ codeType: 'yearType' }).then((res: any) => {
    typeOptions.options3 = res;
  });
  getStashList().then((res: any) => {
    typeOptions.options2 = res;
  });
}
function stashChange(e: number) {
  getStashListInfo({ stashId: e }).then((res: any) => {
    typeOptions.options4 = dedup(res, 'frameNum');
  });
  formState.frameNum = null;
  formState.stashDetailId = null;
}
function frameNumChange(e: number) {
  getStashListInfo({ stashId: formState.stashId, frameNum: e }).then((res: any) => {
    typeOptions.options5 = res;
  });
  formState.stashDetailId = null;
}
function insertWorK() {
  modalOpen.open1 = true;
}
function currentChange(pageNumber: number, pageSize: number) {
  queryParams.value.pageNumber = pageNumber;
  queryParams.value.pageSize = pageSize;
  getLoad();
}
function handleChange(row: any = {}, type: string) {
  switch (type) {
    case 'task':
      formRef.value.validate().then(() => {
        if (formState.warehouseTime != null && formState.warehouseTime.length > 0) {
          formState.warehouseStartTime = formState.warehouseTime[0] + ' 00:00:00';
          formState.warehouseEndTime = formState.warehouseTime[1] + ' 23:59:59';
        }
        createTask({ ...formState, taskType: MATERIAL.YEARTASKTYPE }).then((res: any) => {
          if (res) {
            message.success("新增任务成功");
            getLoad();
          }
          cancel('task');
        })
      });
      break;
    case 'finish':
      modalOpen.modalTit = '完成任务';
      modalOpen.modalDesc = '是否确认完成任务?';
      modalOpen.status = 'finish';
      modalOpen.open2 = true;
      formState = Object.assign(formState, row);
      break;
    case 'finishOk':
      if (modalOpen.status == 'finish') {
        updateTask({ taskId: formState.id }).then((res: any) => {
          if (res) {
            message.success("完成任务");
            getLoad();
          }
          cancel('finish');
        })
      } else if (modalOpen.status == 'remove') {
        removeTask({ taskId: formState.id, taskType: MATERIAL.YEARTASKTYPE }).then((res: any) => {
          if (res) {
            message.success("删除成功");
            getLoad();
          }
          cancel('finish');
        })
      } else {
        message.error("操作失败");
      }
      break;
    case 'details':
      user.setTask(row).then((res: any) => {
        if (res) {
          router.push("/commerprocessyearinfo");
        }
      });
      break;
    case 'remove':
      modalOpen.modalTit = '删除任务';
      modalOpen.modalDesc = '是否确认删除任务?'
      modalOpen.open2 = true;
      modalOpen.status = 'remove';
      formState = Object.assign(formState, row);
      break;
    case 'submit':
      break;
    default:
      break;
  }
}
function cancel(type: string) {
  switch (type) {
    case "task":
      modalOpen.open1 = false;
      for (const key in formState) {
        delete formState[key];
      }
      formState['warehouseTime'] = [];
      formState['frameNum'] = null;
      formState['stashDetailId'] = null;
      typeOptions.options3 = [];
      typeOptions.options4 = [];
      break;
    case "finish":
      modalOpen.open2 = false;
      for (const key in formState) {
        delete formState[key];
      }
      formState['warehouseTime'] = [];
      break;
    default:
      break;
  }
}
getLoad();
getOptionsList();
</script>
<style lang="less" scoped></style>
